/**
 * 微信
*/
const Service = require('egg').Service;

class WechatService extends Service {

  /**
	 * 获取微信access_token
	*/
  async getToken() {
    const { ctx, config } = this;
    let result = {
      data: null,
    };
    const data = {
      grant_type: 'client_credential',
      appid: config.wechat.appid,
      secret: config.wechat.secret,
    };
    try {
      result = await ctx.curl('https://api.weixin.qq.com/cgi-bin/token', {
        dataType: 'json',
        method: 'get',
        data,
      });
      ctx.getLogger('wechatLogger').info('get access_token success', result.data);

      /**
			 * 写入本地json文件,后续应该写入数据库
			*/
      ctx.helper.writeFileContent('app/public/weixinConfig.json', JSON.stringify(
        {
          date: new Date().toLocaleString(),
          message: 'success',
          ...result.data,
        }
      ));

    } catch (error) {
      ctx.getLogger('wechatLogger').error('get access_token error', error);
      throw new Error(`获取微信access_token失败${error}`);
    }
    return result.data;
  }
  /**
   * 发送微信公众号模版信息
   * @param openid
   * @param templateId
  */
  async sendMessage(openid, templateId) {
    const { ctx } = this;
    let result = {
      data: null,
    };
    let body = {};
    const data = {
      touser: openid,
      template_id: templateId || 'vnRkKwTe8HuDVOCBMcN0NIhbdYGYqHE_nOVeLfL_07Q', // 模版id
      topcolor: '#FF0000',
      data: {
        User: {
          value: '黄先生',
          color: '#173177',
        },
        Date: {
          value: new Date().toLocaleString(),
          color: '#173177',
        },
        CardNumber: {
          value: '0426',
          color: '#173177',
        },
        Type: {
          value: '消费',
          color: '#173177',
        },
        Money: {
          value: '人民币1.00元',
          color: '#173177',
        },
        DeadTime: {
          value: new Date().toLocaleString(),
          color: '#173177',
        },
        Left: {
          value: '989,348,493.09',
          color: '#173177',
        },
      },
    };
    try {
      const readFile = await ctx.helper.getFileContent('@public/weixinConfig.json');
      const _token = JSON.parse(readFile).access_token;
      result = await ctx.curl(`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${_token}`, {
        method: 'POST',
        data: JSON.stringify(data),
        dataType: 'json',
      });
      ctx.getLogger('wechatLogger').info('Template message sent successfully', result.data);
      body = {
        code: 200,
        message: 'success',
        result: result.data,
      };
      return body;
    } catch (error) {
      ctx.getLogger('wechatLogger').error('Failed to send template message', error);
      throw new Error(`发送微信公众号模版信息失败${error}`);
    }
  }
}


module.exports = WechatService;
